//
//  HomeViewController.m
//  微博2期
//
//  Created by J on 15/11/17.
//
//

#import "HomeViewController.h"
#import "TitleMenuViewController.h"
#import "DropDownMenu.h"
#import "AFNetworking.h"
#import "AccountTool.h"
#import "TitleButton.h"
#import "Status.h"
#import "User.h"
#import "LoadMoreFooter.h"
@interface HomeViewController ()<DropDownMenuDelegate>
@property(nonatomic,strong)NSMutableArray* statuses;//微博数组 。 一个字典代表一条微博

@end
@implementation HomeViewController


- (NSArray *)statuses{
    
    if (!_statuses) {
        
        self.statuses = [NSMutableArray array];
    }
    return _statuses;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航栏内容
    [self setupNav];
    
    //获取用户信息(昵称)
    
    [self setupUserInfo];

    
    //即成下拉刷新控件
    [self setupDownRefresh];
    //即成上拉刷新控件
    [self setupUpRefresh];
    
    //获得未读数(定时器在主线程中处理 如果tableview在滚动的话定时器不会起作用)
   NSTimer * timer =  [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(setupUnreadCount) userInfo:nil repeats:YES];
    //NSRunLoopCommonModes 意味着主线程也会抽时间处理一下timer (不管主线程是否正在处理其它事件)
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
}

//获得未读数
- (void)setupUnreadCount{
//    NSLog(@"setupUnreadCount");
    //1.请求管理者
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    //2.拼接请求参数
    Account  * account = [AccountTool account];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    
    Status * firtstStatus = [self.statuses firstObject];
    params[@"access_token"]=account.access_token;
    params[@"uid"] = account.uid;
    if (firtstStatus) {//如果第一条微博存在 取出
        //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        params[@"since_id"]=firtstStatus.idstr;
    }
    
    
    [manager GET:@"https://rm.api.weibo.com/2/remind/unread_count.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*  responseObject) {
        //微博未读取数
        //设置未读取微博提醒数字
        NSString * status = [responseObject[@"status"] description];
        if (![status isEqualToString:@"0"]) {
            self.tabBarItem.badgeValue = status;
            [UIApplication sharedApplication].applicationIconBadgeNumber = [status integerValue];
        }
//        NSLog(@"%@",responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        
    }];

    
}



//即成上拉刷新控件
- (void)setupUpRefresh{
 
    self.tableView.tableFooterView = [LoadMoreFooter footer];
}
//即成刷新控件
- (void)setupDownRefresh{
   //原生只有下拉刷新
    UIRefreshControl * control =[[UIRefreshControl alloc]init];
    [control addTarget:self  action:@selector(refreshStateChange:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:control];
    [control beginRefreshing];//开始刷新 仅仅是显示刷新状态 并不会触发UIControlEventValueChanged 状态  只有用户手动下拉才会UIControlEventValueChanged 触发
    [self refreshStateChange:control];//传控件
}

- (void)refreshStateChange:(UIRefreshControl*)control{
    
    //1.请求管理者
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    //2.拼接请求参数
    Account  * account = [AccountTool account];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];

    Status * firtstStatus = [self.statuses firstObject];
    params[@"access_token"]=account.access_token;
    if (firtstStatus) {//如果第一条微博存在 取出
        //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        params[@"since_id"]=firtstStatus.idstr;
    }
   

    [manager GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*  responseObject) {
        
        NSArray * newStatus = [Status objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        //插入最新数据
        [self.statuses insertObjects:newStatus atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, newStatus.count)]];

        //刷新表格
        [self.tableView reloadData];
        
        //结束刷新
        [control endRefreshing];
        //显示最新微博的数量动画
        [self showNewStatusCount:newStatus.count];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        //结束刷新
        [control endRefreshing];
        NSLog(@"%@",error);
        
    }];
    
    
}
/**
 *
 *
 *  @param count 显示最新微博的数量
 */
- (void)showNewStatusCount:(NSInteger)count{
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    self.tabBarItem.badgeValue = nil;//刷新之后未读数设置为空
    //1.创建label
    UILabel * label  = [[UILabel alloc]init];
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];//图片转化为颜色
    label.width = [UIScreen mainScreen].bounds.size.width;
    label.height = 35;
    label.y = 64 - label.height;
    //2. 设置其他属性
    if (!count) {
        label.text = [NSString stringWithFormat:@"共有%d条新的微博数据",0];
    }else{
        label.text = [NSString stringWithFormat:@"共有%d条新的微博数据",count];
    }
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:16];
    label.textAlignment = NSTextAlignmentCenter;
    //3.添加
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];//盖在导航栏下面
    //动画
    //先利用1s的时候 让lebel往下移动一个高度
    CGFloat duration = 1.0;
    [UIView animateWithDuration:duration animations:^{
        label.hidden = NO;

//        label.y +=label.height;
        
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
    } completion:^(BOOL finished) {
        
        //延迟1s后让label恢复到之前位置
        [UIView animateWithDuration:duration delay:duration options:UIViewAnimationOptionCurveEaseOut animations:^{
//            label.y -=label.height;
            label.transform = CGAffineTransformIdentity;//清空transform
        } completion:^(BOOL finished) {
            
            [label removeFromSuperview];//动画完毕销毁
        }];

    }];
    
}


//获取用户信息(昵称)

- (void)setupUserInfo{
    
//    https://api.weibo.com/2/users/show.json
//    access_token&uid
    
    
    //1.请求管理者
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    //2.拼接请求参数
    Account  * account = [AccountTool account];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"uid"]=account.uid;
    params[@"access_token"]=account.access_token;
       [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*  responseObject) {

        NSString * name =    responseObject[@"screen_name"];
           UIButton * titleButotn = (UIButton*)self.navigationItem.titleView;
           [titleButotn setTitle:name forState:UIControlStateNormal];//标题文字到按钮

           //存储昵称到沙盒
           account.name = name;
           [AccountTool saveAccount:account];
       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);

    }];
    
    
    
}
//设置导航栏内容

- (void)setupNav{
    
    //设置导航栏内容
    //设置左边返回按钮
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(friendSearch) image:@"navigationbar_friendsearch" highImage:@"navigationbar_friendsearch_highlighted"];
    
    //设置右边更多按钮
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(pop) image:@"navigationbar_pop" highImage:@"navigationbar_pop_highlighted"];
    
    //中间标题按钮
    TitleButton * titleButton = [TitleButton buttonWithType:UIButtonTypeCustom];
 
    //按钮设置文字要用状态的方式
    NSString* name = [AccountTool account].name;
    
    [titleButton setTitle:name?name:@"首页" forState:UIControlStateNormal];
    //监听标题点击
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.titleView = titleButton;

}
- (void)titleClick:(UIButton*)button{
    //显示下拉菜单
   DropDownMenu* menu =  [DropDownMenu menu];
    menu.delegate = self;
    TitleMenuViewController * vc= [[TitleMenuViewController alloc]init];
    vc.view.height = 44*3;
    vc.view.width = 150;

    menu.contentViewcontroller = vc;
     // 显示
    [menu showFrom:button];

  }


#pragma mark --改变按钮的图片
- (void)dropdownMenuDidDismiss:(DropDownMenu *)menu{
    UIButton * button = (UIButton*)self.navigationItem.titleView;
    //让箭头向下
    button.selected = NO;
    
}


//下拉菜单显示了
-(void)dropdownMenuDidShow:(DropDownMenu *)menu{
    UIButton * button = (UIButton*)self.navigationItem.titleView;
    //    4.让箭头向上
    button.selected = YES;

}

- (void)friendSearch{
    //这里sel本身就是一个导航控制器 self.navigationController ==null
}

- (void)pop{
    [self.navigationController popToRootViewControllerAnimated:YES];//返回根控制器
    


}



#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    
    
    return self.statuses.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ID"];
    }
    //取出row对应的微博字典
    Status * status =self.statuses[indexPath.row];
    
    //取出用户名
    cell.textLabel.text = status.user.name;
    //设置头像
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:status.user.profile_image_url]];
    //微博内容 
    cell.detailTextLabel.text =status.text;

    return cell;
    
    
    
}
@end
